package com.lvchen.common.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by 律晨 on 2018/5/24.
 */
public class DisyplayUtils {

    /**
     * Convert the dip to the pixel
     *
     * @param dpValue
     * @return
     */
    public static int dipToPixel(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * Convert the pixel to the dip
     *
     * @param pxValue
     * @return
     */
    public static int pixelToDip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * Get display metrics
     *
     * @return
     */
    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        return dm;
    }

    public static int getDensityDpi(Context context) {
        return context.getResources().getDisplayMetrics().densityDpi;
    }

    /**
     * Get the screen height
     *
     * @return
     */
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * Get the screen width
     *
     * @return
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     *
     * @return Get The Screen Density
     */
    public static float getScreenDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    /**
     * Get the real size related to 640
     *
     * @return
     */
    public static int getRealSize(Context context, int value) {
        return (int) (getScreenWidth(context) / 640.0F * value);
    }

    /**
     * 获取屏幕宽度和高度，单位为px
     * @param context
     * @return
     */
    public static Point getScreenMetrics(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int h_screen = dm.heightPixels;
        return new Point(w_screen, h_screen);

    }

    /**
     * 获得当前界面所在xml文件的最根view
     * [不可见的FrameLayout]
     * [窗口绘制完成才能获取到有效值]
     * @param activity
     * @return
     */
    public static View getContentView(Activity activity){
        return activity.getWindow().getDecorView().findViewById(android.R.id.content);
    }

    /**
     * 获取屏幕长宽比
     * @param context
     * @return
     */
    public static float getScreenRate(Context context){
        Point P = getScreenMetrics(context);
        float H = P.y;
        float W = P.x;
        return (H/W);
    }

    /**
     * dip转px
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dipValue * scale + 0.5f);
    }

    /**
     * px转dip
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(pxValue / scale + 0.5f);
    }

    /**
     * 旋转Bitmap
     * @param b
     * @param rotateDegree
     * @return
     */
    public static Bitmap getRotateBitmap(Bitmap b, float rotateDegree){
        Matrix matrix = new Matrix();
        matrix.postRotate((float)rotateDegree);
        Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, false);
        return rotaBitmap;
    }

    private static   String storagePath = "";
    /**初始化保存路径
     * @return
     */
    private static String initPath(){
        if(storagePath.equals("")){
            storagePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/lvchen/";
            File f = new File(storagePath);
            if(!f.exists()){
                f.mkdir();
            }
        }
        return storagePath;
    }

    /**保存Bitmap到sdcard
     * @param b
     */
    public static String saveBitmap(Context context,Bitmap b,int flag){
        String path = initPath();

        String filename="";
        SimpleDateFormat formatter    =   new    SimpleDateFormat    ("yyyyMMddHHmmss");
        Date curDate    =   new Date(System.currentTimeMillis());//获取当前时间
        String    str    =    formatter.format(curDate);
        if(flag==1){
            filename = path +str+"front.jpg";
        }else if(flag==2) {
            filename = path +str+"back.jpg";
        }else if(flag==3){
            filename = path +str+"front.jpg";
        }else if(flag==4) {
            filename = path +str+"back.jpg";
        }else if(flag==5){
            filename = path +str+"front.jpg";
        }else if(flag==6) {
            filename = path +str+"back.jpg";
        }else if(flag==7){
            filename = path +str+"front.jpg";
        }else if(flag==8) {
            filename = path +str+"back.jpg";
        }else {
            filename = path +str+"bank.jpg";
        }
        ScannerByReceiver(context,filename);
        try {
            FileOutputStream fout = new FileOutputStream(filename);
            BufferedOutputStream bos = new BufferedOutputStream(fout);
            b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;

    }

    private static void ScannerByReceiver(Context context, String path) {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        System.out.println("--------------更新图库成功-----------------");
        MediaScannerConnection.scanFile(context,new String[] { path.toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
            }
        });
    }

}